package cn.tedu.v6;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.rmi.ConnectException;
import java.util.Scanner;

public class Client {
    private Socket socket;
    private static final String Host="127.0.0.1";
    private static final Integer PORT=5555;
    private PrintWriter pw;
    private BufferedReader br;

    public Client() {
        try {
            socket = new Socket(Host, PORT);
            br = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF8"));
            pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), "UTF8")), true);
        } catch (NullPointerException e) {
            System.out.println("友情提示：IP传入错误导致连接失败");
        } catch (UnknownHostException e) {
            System.out.println("友情提示：IP传入错误");
        } catch (ConnectException e) {
            System.out.println("客户端连接失败：建议检查IP或者端口号");
        } catch (IOException e) {
            System.out.println("客户端连接服务器端失败，提示：检查IP/端口");
        }
    }

    public void start()  {
        //与服务器端交互---参考Server
        System.out.println("欢迎使用delight牌QQ聊天室");
        Scanner input=new Scanner(System.in);
        try {
            //1.读入服务器端："请输入用户名："
            String serverMessage=br.readLine();
            //1.1显示"请输入用户名："
            System.out.println(serverMessage);
            //1.2用户输入--用户名
            String username=input.nextLine();
            //1.3用户输入的用户名--写出给服务器端
            pw.println(username);
            //2.1读入服务器发来"请输入密码："
            serverMessage=br.readLine();
            System.out.println(serverMessage);
            //2.2用户输入--密码--写出给服务器端
            String password=input.nextLine();
            pw.println(password);
            //3.登录之后【登录成功、登录失败】--才可以聊天
            //字符串方法：startsWith() 返回值 boolean 前缀名称一致true
            serverMessage=br.readLine();//读入【登录成功、登录失败】
            if (serverMessage.startsWith("登录成功")){
                //封一个客户端的：读写流---chat聊天
                System.out.println("登录成功，欢迎进入聊天室");
                chat();
            }else {
                serverMessage.startsWith("登录失败");
                System.out.println("登录失败，用户名或者密码错误");
                socket.close();
            }
        } catch (IOException e) {
            System.out.println("客户端断开连接");
        } finally {
            if (br!=null)
                try {
                    br.close();
                } catch (IOException e) {
                    System.out.println("客户端关闭失败");
                }
            if (pw != null)
                pw.close();
            if (socket != null && !socket.isClosed())
                try {
                    socket.close();
                } catch (IOException e) {
                    System.out.println("通讯关闭失败");
                }
        }
    }
    //封装一个针对聊天功能：读写 chat()
    private void chat() {
        new Thread(() -> {
            try {
                String message;
                while ((message = br.readLine()) != null) {
                    //1.如果服务器端输入exit 客户端说：服务器端说happy退出聊天室
                    if ("exit".equalsIgnoreCase(message)) {
                        System.out.println("服务器端说：happy退出聊天室");
                        break;
                    } else {
                        //2.反之，服务器继续输入
                        System.out.println("服务器端说：" + message);
                    }
                    System.out.println("客户端请输入：服务器端说：请输入消息（输入exit退出）");
                }
            } catch (IOException e) {
                System.out.println("服务器端读入失败");
            }
        }).start();

        Scanner input = new Scanner(System.in);
        while (true) {
            System.out.println("客户端请输入：");

            while (true) {
                String line = input.nextLine();
                //  pw.println("客户端说：" + line);

                //3.如果客户端写出"exit"客户端"退出聊天室"关闭进程
                if ("exit".equalsIgnoreCase(line)) {
                    System.out.println("退出聊天室");
                    System.exit(0);
                } else {
                    //4.反之，客户端继续写出
                    pw.println("客户端请输入" + line);
                }
            }
        }
    }
    public static void main(String[] args) {
        new Client().start();
    }
}
